import React, { Component } from 'react';
import { toJS } from 'mobx';
import { observer, inject } from 'mobx-react';
import { withRouter, Route } from 'react-router-dom';
import { Icon, Popover, ActivityIndicator, Result, Tools, PhotoSwipe, Modal, Schedule } from 'weaver-mobile';
import { ListAdvanced, ListViewPage, TabPage, RouteLayout, Reply, SearchAdvanced, BrowserHrm, Browser } from 'weaver-mobile-page';
import ContactHomePageStore from '../../stores/list/ContactHomePageStore';
import ContactList from '../list/ContactList';
import WorkplanList from '../list/WorkplanList';

const Item = Popover.Item;
const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
  wrapProps = {
    onTouchStart: e => e.preventDefault(),
  };
}
const alert = Modal.alert;
const getLabel = Tools.getLabel;

// @inject('contactHomeListStore')
@withRouter
@observer
export default class ContactHomePage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      store : new ContactHomePageStore(),
      span: [3, 1],
      curParams: {chanceId:"",customerId:""},
      searchAdIcon:"filter-o"
    };
  }

  componentWillMount(){
    const {params,match} = this.props;
    const ps = params ? params : match.params;
    this.state.store.doNew(this,{type:"crm_contact_home",...ps});
  }

  componentDidMount() {
    this.state.store.doInit();    
  }

  componentWillUnmount() {
    this.state.store.doClear();
  }

  handleSelect = (opt,index) => {
    const {store} = this.state;
    const {listTabIndex,subType} = store;
    if(listTabIndex === "my"){
      if(index === 0){
        if("contact" === subType){
          // 添加联系
          this.listRef.addContact();
          store.visibleChange(false);
        }else{
          // 添加计划
          this.listRef.addWorkplan();
          store.visibleChange(false);
        }      
      }
    }else if(listTabIndex === "subordinate"){
      if(index === 0){
        // 按指定下属查看
        const { subordinateBrowserStore } = store;
        this.props.history.push(subordinateBrowserStore.path);
        store.visibleChange(false);
      }
    }else if(listTabIndex === "all"){
      if(index === 0){
        // 按指定人员查看
        const { createrIdBrowserStore } = store;
        this.props.history.push(createrIdBrowserStore.path);
        store.visibleChange(false);        
      }else if(index === 1){
        // 按指定部门查看
        const { createrIdDeptBrowserStore } = store;
        this.props.history.push(createrIdDeptBrowserStore.path);
        store.visibleChange(false);        
      }else if(index === 2){
        if("contact" === subType){
          // 添加联系
          this.listRef.addContact();
          store.visibleChange(false);
        }else{
          // 添加计划
          this.listRef.addWorkplan();
          store.visibleChange(false);
        }  
      }
    }
  }

  handleVisibleChange = (visible) => {
    const {store} = this.state;
    store.visibleChange(visible);
  };

  render() {
    const {store} = this.state;
    const {initResponsed,initSuccessed,initFailedMsg} = store;
    
    if(initResponsed){
      if(initSuccessed){
        const { listTab, listTabIndex, listAd, list, params, subType, popover, visible, overlay, defaultDate, extra, searchParams, scheduleMode, searchAd, currentMonth, createrIdBrowserStore, createrIdDeptBrowserStore, subordinateBrowserStore} = store;
        const { span, curParams, searchAdIcon } = this.state;

        const popoverProps = {
          visible,
          overlay,
          onSelect: this.handleSelect,
          onVisibleChange: this.handleVisibleChange,
        };

        let tabProps = {
          page:listTabIndex,
          swipeable:true,
          onChange: (tab) => {
            store.resetFields();
            this.setState({searchAdIcon:"filter-o"});   
            store.topTabChange(tab.key);
          }
        };

        let iconProps = {};
        if(searchAdIcon == "filter-o-hot"){
          iconProps.className = "crm-searchAd-icon";
        }

        let btns = [];
        btns.push(<Icon type={searchAdIcon} {...iconProps} onClick={this.showSearchCondition.bind(this)}/>);
        let currentTabTitle;
        if(listTabIndex === "all" || listTabIndex === "subordinate"){
          // 如果高级搜索中创建人或创建人部门条件有值
          const { formParams } = searchAd.form;
          for(let p in formParams){
            if(p === "createrId" && formParams[p] !== ""){
              currentTabTitle = formParams["createrIdspan"];
              break;
            }
            if(p === "createrDeptId" && formParams[p] !== ""){
              currentTabTitle = formParams["createrDeptIdspan"];
              break;
            }
          }
        }

        let listCom;
        if("contact" == subType){
          listCom = <ContactList params={{ rightType: listTabIndex, ...searchParams}} onRef={this.onRef} saveCallBack={this.saveCallBack.bind(this)}></ContactList>;
        }else{
          listCom = <WorkplanList params={{ rightType: listTabIndex, ...searchParams}} onRef={this.onRef} saveCallBack={this.saveCallBack.bind(this)}></WorkplanList>;
        }

        return (
            <div className="crm-homepage">
                <TabPage
                  btns={btns}
                  span={span}
                  tabs={listTab}
                  tabProps={tabProps}
                  popover={popover}
                  popoverProps={popoverProps}
                >
                </TabPage>
                <Schedule
                  mode={scheduleMode}
                  extraTitle={currentTabTitle}
                  defaultDate={new Date(defaultDate)}
                  dateExtra={toJS(extra)}
                  weekStart={7}
                  onMonthChange={(month, range, title) =>{
                      this.listRef.resetListHeight();                      
                      const dateArr = title.split(".");
                      let monthFormat = dateArr[0];
                      if(parseInt(dateArr[1]) < 10){
                        monthFormat += "-"+"0"+dateArr[1];                        
                      }else{
                        monthFormat += "-"+dateArr[1];
                      }
                      store.monthChange(monthFormat);
                      // 切换月份
                      if(monthFormat !== currentMonth){
                        store.getCircleDot();
                      }
                    }                    
                  }
                  onSelect={(v) => {
                    // 获取高级搜索参数
                    const { formParams } = searchAd.form;
                    const searchParams = {fromDate:v,toDate:v,...formParams}; 
                    store.setSearchParams(searchParams);
                  }}
                  hideLunar={true}
                />
                <div className="crm_contact_list" style={{marginTop:"15px"}}>
                  {listCom}
                </div>
                <SearchAdvanced
                  store={searchAd}
                  onSubmit={()=>{
                    this.doSearch();
                  }}
                  onReset={()=>{
                    this.setState({searchAdIcon:"filter-o"});
                  }}
                />
                <div className="crm-hide-area">
                <BrowserHrm
                  // label="人力单选"
                  store={createrIdBrowserStore}
                  hasAdvanceSerach
                  isSingle={true}
                  type={1}
                  onChange={(value,valueSpan,valueArray) => {
                    if (value) {
                      // 清空高级搜索中的其他条件
                      searchAd.form.resetFields();
                      searchAd.form.updateFields({createrId:{value:valueArray}});
                      this.doSearch();
                    }
                  }}
                />
                <Browser
                  // label="部门单选"
                  store={createrIdDeptBrowserStore}
                  hasAdvanceSerach
                  isSingle={true}
                  type={"4"}
                  // tabs={tabsArr}
                  onChange={(value,valueSpan,valueArray) => {
                    if(value){
                      // 清空高级搜索中的其他条件
                      searchAd.form.resetFields();
                      searchAd.form.updateFields({createrDeptId:{value:valueArray}});
                      this.doSearch();
                    }
                  }}
                />
                <BrowserHrm
                  // label="下属单选"
                  store={subordinateBrowserStore} 
                  hasAdvanceSerach
                  type={"1"}
                  isSingle={true}
                  tabs={[{name:"我的下属",key:"3"}]}
                  dataParams={{ cmd: 'branch' }}
                  onChange={(value,valueSpan,valueArray) => {
                    if(value){
                      // 清空高级搜索中的其他条件
                      searchAd.form.resetFields();
                      searchAd.form.updateFields({createrId:{value:valueArray}});                      
                      this.doSearch();
                    }
                  }}
                />
              </div>
            </div>
        );
      }else{
        return (
          <div>
              <Result
                img={<Icon type="cross-circle-o" className="crm_commerce_initFailedMsg" style={{ fill: '#F13642' }} />}
                title=""
                message={initFailedMsg}
              />
          </div>);
      }
    }else{
      return <div className="crm-bg-loading"><ActivityIndicator text="Loading..."/></div>;
    }
  }

  doSearch = () =>{
    const {store} = this.state;
    const {searchAd,searchParams} = store;
    // 获取高级搜索参数
    const { formParams } = searchAd.form;
    let hasValue = false;
    for(let p in formParams){
      if(formParams[p] !== ""){
        hasValue = true;
        break;
      }
    }
    if(hasValue){
      this.setState({searchAdIcon:"filter-o-hot"});
    }else{
      this.setState({searchAdIcon:"filter-o"});
    }
    const newParams = {...searchParams,...formParams}; 
    store.getCircleDot();
    store.setSearchParams(newParams);
  }

  onRef = (ref) => {
    this.listRef = ref;
  }

  showSearchCondition(){
    const {store} = this.state;
    const {searchAd,listTabIndex} = store;
    this.props.history.push(searchAd.path);
  }

  saveCallBack = () => {
    const {store} = this.state;
    store.getCircleDot();
  }  
}